package com.littlebee.storychild.ui;

import android.animation.Animator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.littlebee.storychild.R;
import com.littlebee.storychild.common.utils.BabyStoryPlanEntry;
import com.littlebee.storychild.common.utils.Constant;
import com.littlebee.storychild.common.utils.DateUtils;
import com.littlebee.storychild.common.utils.NetWorkUtils;
import com.littlebee.storychild.common.utils.SoundMeter;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.ui.entry.Cartoons;
import com.littlebee.storychild.ui.entry.StorysEntry;
import com.littlebee.storychild.ui.entry.User;
import com.zss.library.activity.ZFrameActivity;
import com.zss.library.animator.Techniques;
import com.zss.library.animator.YoYo;
import com.zss.library.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.im.android.api.JMessageClient;

/**
 *
 */
public class RecStoryToMotherDialog extends Dialog implements View.OnClickListener , GestureDetector.OnGestureListener{
    private GestureDetector detector;


    private TextView toSend,againRec;
    private TextView recOrPause;

    Activity mContext;
    BabyStoryPlanEntry hid;
    //Cartoons hid1;
    StorysEntry hid2;
    private String fileName;
    private View rcChat_popup;
    private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
            voice_rcd_hint_tooshort;
    private SoundMeter mSensor;

    float y1 = 0;
    float y2 = 0;
    private boolean isShosrt = false;
    private String voiceName;
    private int flag = 1;

    private Handler mHandler = new Handler();
    private long startVoiceT, endVoiceT;
    private ImageView volume;
    private TextView tab_order_tv;
    private RelativeLayout show_bg;
    private LinearLayout show_ly_order;
    ImageView imageView1,imageView2;
    /**录音提示类型 0 故事选择 1 英语动画片*/
    private int type;

    public RecStoryToMotherDialog(Activity context, BabyStoryPlanEntry hId,int type) {
        super(context, com.zss.library.R.style.CommonDialog);
        setContentView(R.layout.fragment_demand_order);
        this.mContext=context;
        this.type=type;
        detector = new GestureDetector(mContext, this);

        this.hid=hId;
        int width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setLayout(width, width);
        initView();
        initData();
    }

    public RecStoryToMotherDialog(Activity context, StorysEntry hId, int type) {
        super(context, com.zss.library.R.style.CommonDialog);
        setContentView(R.layout.fragment_demand_order);
        this.mContext=context;
        this.type=type;
        detector = new GestureDetector(mContext, this);
        this.hid2=hId;
        int width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setLayout(width, width);
        initView();
        initData();
    }
    public void initView() {
        tab_order_tv=(TextView)findViewById(R.id.tab_order_tv);
        if(type==0){
            tab_order_tv.setText("我想听 "+hid.getStoryname());

        }else{

        }
        show_bg=(RelativeLayout)findViewById(R.id.show_bg);
        show_bg.setOnClickListener(this);
        show_ly_order=(LinearLayout)findViewById(R.id.show_ly_order);
        show_ly_order.setOnClickListener(this);
        rcChat_popup = findViewById(R.id.rcChat_popup);
        imageView1=(ImageView) findViewById(R.id.image_1);
        imageView2=(ImageView) findViewById(R.id.image_2);
        voice_rcd_hint_rcding = (LinearLayout)
                findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) findViewById(R.id.voice_rcd_hint_tooshort);
        volume = (ImageView) findViewById(R.id.volume);
        //volume.setOnClickListener(this);
        mSensor = new SoundMeter();
        toSend = (TextView)  findViewById(R.id.order_reward);
        toSend.setOnClickListener(this);
        againRec = (TextView)  findViewById(R.id.order_res);
        againRec.setOnClickListener(this);
        recOrPause=(TextView)findViewById(R.id.rec_tv);
        volume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flag==1){
                    LogUtils.i("XHX", "录音3");
                    recOrPause.setText("松开 结束");
                    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            if (!isShosrt) {
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding.setVisibility(View.VISIBLE);
                            }
                        }
                    }, 300);
                    startAnim1();
                    startVoiceT = System.currentTimeMillis();
                    User user=Utils.getUserEntry();
                    voiceName = user.getMobile() + "-" + DateUtils.getTimeDayNull(System.currentTimeMillis()) +".mp3";
                    start(voiceName);
                    flag = 2;
                }else{
                    initStop();
                }
            }
        });
    }

    private void initStop() {
        stop();
        endVoiceT = System.currentTimeMillis();
        flag = 1;
        int time = (int) ((endVoiceT - startVoiceT) / 1000);
        LogUtils.i("XHX", "时长：开始" + startVoiceT + "；结束：" + endVoiceT + "时长：" + time);
        if (time < 1) {
            isShosrt = true;
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    voice_rcd_hint_tooshort
                            .setVisibility(View.GONE);
                    //rcChat_popup.setVisibility(View.GONE);
                    isShosrt = false;
                }
            }, 500);
            dismiss();
            return;
        }
        LogUtils.i("XHX", "时长11111：");
        fileName=android.os.Environment.getExternalStorageDirectory() + "/"
                + voiceName;
        if(TextUtils.isEmpty(fileName)){
            ToastUtil.displayShortToast("请上传录音");
            return ;
        }
        imageView1.setVisibility(View.GONE);
        imageView2.setVisibility(View.GONE);
        uploadStoryInfo();
    }

    public void startAnim1() {
        YoYo.with(Techniques.Pulse).onStart(new YoYo.AnimatorCallback() {
            @Override
            public void call(Animator animator) {
                YoYo.with(Techniques.Pulse).onEnd(new YoYo.AnimatorCallback() {
                    @Override
                    public void call(Animator animator) {
                        if (true) {
                            startAnim1();
                        }
                    }
                }).playOn(imageView2);
            }
        }).playOn(imageView1);;
    }


    private static final int POLL_INTERVAL = 300;
    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            if((System.currentTimeMillis()-startVoiceT)/1000>=10){
                initStop();
            }
            //触发停止了就不要自动发送语音了。。。
            if (flag != 1) {
                mHandler.postDelayed(mPollTask, POLL_INTERVAL);
            }
        }
    };
    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    private void stop() throws RuntimeException{
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        mSensor.stop();
        volume.setImageResource(R.drawable.ease_record_animate_02);
    }

    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.ease_record_animate_02);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.ease_record_animate_04);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.ease_record_animate_07);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.ease_record_animate_09);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.ease_record_animate_11);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.ease_record_animate_13);
                break;
            default:
                volume.setImageResource(R.drawable.ease_record_animate_14);
                break;
        }
    }
    public void initData() {


    }
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.order_reward:
                if(TextUtils.isEmpty(fileName)){
                    ToastUtil.displayShortToast("请上传录音");
                    return;
                }
                uploadStoryInfo();
                break;
            case R.id.order_res:
                fileName="";
                break;
            case R.id.volume:
                if(TextUtils.isEmpty(fileName)){
                    ToastUtil.displayShortToast("还没有录音哦");
                    return;
                }
                startPlayer(fileName);
                break;
            case R.id.show_bg:
                dismiss();
                break;
            case R.id.show_ly_order:
            break;


        }
    }
    private MediaPlayer mPlayer = null;

    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaRelease();

            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
    /**
     * 上传宝宝感谢语
     */
    protected void setThanksAudio(String url) {
        Map<String, String> hashMap = new HashMap<>();
        User user= Utils.getUserEntry();
        hashMap.put("deviceid", user.getMobile());
        hashMap.put("audiourl", url);
        NetWorkUtils.post(mContext, "setthanksaudio", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                LogUtils.i("XHX", "XHX"+result);
                Intent intent = new Intent(mContext, PlayerStoryInfoActivity.class);
                intent.putExtra("info", hid2);
                mContext.startActivity(intent);
                dismiss();
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils
                        .i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("发送失败");
                dismiss();
            }
        });
    }
    /**
     * 上传宝宝选择的数据
     */
    protected void sendToday(String url) {
        Map<String, String> hashMap = new HashMap<>();
        User user= Utils.getUserEntry();
        hashMap.put("deviceid", user.getMobile());
        hashMap.put("wantstoryid", hid.getStoryid());
        hashMap.put("wantaudiomsgurl", url);
        LogUtils.i("XHX", "ID:HB60000000" + ";wantstoryid:" + hid + ";wantaudiomsgurl:" + "http://47.92.37.125:9090/piecefile/18611697983-20170831102605.mp3");
        NetWorkUtils.post(mContext, "setbabywantstory", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                LogUtils.i("XHX", "XHX"+result);
                ToastUtil.displayShortToast("发送成功");
                dismiss();
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("发送失败");
                dismiss();
            }
        });
    }
    /*
     * 上传录音文件
     *
     * */
    public void uploadStoryInfo() {
        NetWorkUtils.upload(mContext, Constant.UPLOAD_PATH, new File(fileName), new NetWorkUtils.IProgressListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                LogUtils.i("XHX", "ACTIVITY接受到了：" + result.toString());
                try {
                    String res = resObj.getJSONObject("response").optString("url");
                    if(type==0) {
                        sendToday(res);
                    }else if(type==2){
                        setThanksAudio(res);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onProgress(int index, long totalBytes, long surplusBytes, boolean done) {
                LogUtils.i("XHX", "进度：" + surplusBytes + ";总进度：" + totalBytes);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "ACTIVITY接受到了失败：" + result.toString());
                ToastUtil.displayShortToast("上传故事失败");

            }
        });

    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public void dismiss() {
        mediaRelease();
        super.dismiss();
    }
}
